import { getPlayerData, isPlayerExist, storagePlayerData } from '../l.js'
import puppeteer from "../../../lib/puppeteer/puppeteer.js";

export class Fs extends plugin {
    constructor() {
        super({
            name: '[Fs]化肥商店',
            dsc: '化肥商店',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^(#|\/)?化肥(商店|商城|列表)$/, fnc: 'fertilizerList' },
                { reg: /^(#|\/)?购买化肥\s*(.*?)(?:\s*\*\s*(\d+))?$/, fnc: 'buyFertilizer' },
                { reg: /^(#|\/)?化肥背包$/, fnc: 'fertilizerBag' },
                { reg: /^(#|\/)?施肥\*(\d+)\s*(\S+)$/, fnc: 'applyFertilizer' },
                { reg: /^(#|\/)?(一键|全部)施肥\s*(\S+)$/, fnc: 'applyAllFertilizer' }
            ]
        })
    }

    async fertilizerList(e) {
        const fertilizerData = [
            { name: '普通化肥', price: 100, effect: 1.2 },
            { name: '高级化肥', price: 300, effect: 1.5 },
            { name: '特级化肥', price: 1000, effect: 2 }
        ]

        const image = await puppeteer.screenshot('化肥商店', {
            tplFile: 'plugins/Farming-Simulator/resources/html/fertilizerShop.html',
            info: fertilizerData,
        })
        return e.reply([image])
    }

    async buyFertilizer(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply('无玩家信息，请发送[领取田地]')
        }

        const [, , FERTILIZER_NAME_RAW, NUMBER = "1"] = e.msg.match(/^(#|\/)?购买化肥\s*(.*?)(?:\s*\*\s*(\d+))?$/)
        const FERTILIZER_NAME = FERTILIZER_NAME_RAW.trim()
        const amount = parseInt(NUMBER)

        const fertilizerData = {
            '普通化肥': { price: 100, effect: 1.2 },
            '高级化肥': { price: 300, effect: 1.5 },
            '特级化肥': { price: 1000, effect: 2 }
        }

        if (!fertilizerData[FERTILIZER_NAME]) {
            return e.reply('没有这种化肥哦，请发送[化肥商店]查看可用化肥')
        }

        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        const totalPrice = fertilizerData[FERTILIZER_NAME].price * amount

        if (PLAYER_DATA['capital'] < totalPrice) {
            return e.reply(`💰不足，需要${totalPrice}金币`)
        }

        if (!PLAYER_DATA['fertilizer']) {
            PLAYER_DATA['fertilizer'] = {}
        }
        if (!PLAYER_DATA['fertilizer'][FERTILIZER_NAME]) {
            PLAYER_DATA['fertilizer'][FERTILIZER_NAME] = 0
        }

        PLAYER_DATA['fertilizer'][FERTILIZER_NAME] += amount
        PLAYER_DATA['capital'] -= totalPrice
        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        return e.reply([
            '购买成功!',
            `购买了${amount}个${FERTILIZER_NAME}`,
            `花费💰[${totalPrice}]`
        ].join('\n'))
    }

    async fertilizerBag(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply('无玩家信息，请发送[领取田地]')
        }

        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        if (!PLAYER_DATA['fertilizer']) {
            return e.reply('您还没有购买过化肥喵~')
        }

        const fertilizerList = Object.entries(PLAYER_DATA['fertilizer']).map(([name, count]) => ({
            name,
            count,
            effect: {
                '普通化肥': 1.2,
                '高级化肥': 1.5,
                '特级化肥': 2
            }[name]
        }))

        const image = await puppeteer.screenshot('化肥背包', {
            tplFile: 'plugins/Farming-Simulator/resources/html/fertilizerBag.html',
            info: fertilizerList,
        })
        return e.reply([image])
    }

    async applyFertilizer(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply('无玩家信息，请发送[领取田地]')
        }

        const [, , SERIAL_NUMBER, FERTILIZER_NAME] = e.msg.match(/^(#|\/)?施肥\*(\d+)\s*(\S+)$/)
        const PLAYER_DATA = await getPlayerData(PLAYER_ID)

        if (PLAYER_DATA['frame'].length < SERIAL_NUMBER) {
            return e.reply('你没有此格子喵~')
        }

        const frame = PLAYER_DATA['frame'][SERIAL_NUMBER - 1]
        if (!frame['start']) {
            return e.reply('该格子未种植作物喵~')
        }

        if (frame['fertilizer']) {
            return e.reply('该格子已经使用过化肥了喵~')
        }

        if (!PLAYER_DATA['fertilizer'] || !PLAYER_DATA['fertilizer'][FERTILIZER_NAME]) {
            return e.reply('您没有这种化肥，请先购买')
        }

        if (PLAYER_DATA['fertilizer'][FERTILIZER_NAME] <= 0) {
            return e.reply('化肥数量不足')
        }

        const fertilizerEffect = {
            '普通化肥': 1.1, // 中途施肥效果减半
            '高级化肥': 1.25,
            '特级化肥': 1.5
        }

        frame['fertilizer'] = FERTILIZER_NAME
        frame['number'] = Math.floor(frame['number'] * fertilizerEffect[FERTILIZER_NAME])
        PLAYER_DATA['fertilizer'][FERTILIZER_NAME]--

        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        return e.reply([
            '施肥成功!',
            `在格子[${SERIAL_NUMBER}]的${frame['name']}上施了${FERTILIZER_NAME}`,
            `由于是中途施肥，效果减半`,
            `预计收获量提升至${frame['number']}个`
        ].join('\n'))
    }

    async applyAllFertilizer(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply('无玩家信息，请发送[领取田地]')
        }

        const [, , , FERTILIZER_NAME] = e.msg.match(/^(#|\/)?(一键|全部)施肥\s*(\S+)$/)
        const PLAYER_DATA = await getPlayerData(PLAYER_ID)

        if (!PLAYER_DATA['fertilizer'] || !PLAYER_DATA['fertilizer'][FERTILIZER_NAME]) {
            return e.reply('您没有这种化肥，请先购买')
        }

        const fertilizerEffect = {
            '普通化肥': 1.1,
            '高级化肥': 1.25,
            '特级化肥': 1.5
        }

        if (!fertilizerEffect[FERTILIZER_NAME]) {
            return e.reply('没有这种化肥哦，请发送[化肥商店]查看可用化肥')
        }

        let availableFertilizer = PLAYER_DATA['fertilizer'][FERTILIZER_NAME]
        if (availableFertilizer <= 0) {
            return e.reply('化肥数量不足')
        }

        let successCount = 0
        let summary = []

        for (let i = 0; i < PLAYER_DATA['frame'].length; i++) {
            const frame = PLAYER_DATA['frame'][i]
            if (!frame['start'] || frame['fertilizer'] || availableFertilizer <= 0) {
                continue
            }

            frame['fertilizer'] = FERTILIZER_NAME
            frame['number'] = Math.floor(frame['number'] * fertilizerEffect[FERTILIZER_NAME])
            availableFertilizer--
            successCount++
        }

        if (successCount === 0) {
            return e.reply('没有可以施肥的作物喵~')
        }

        PLAYER_DATA['fertilizer'][FERTILIZER_NAME] -= successCount
        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        return e.reply([
            `一键施肥成功！`,
            `使用了${successCount}个${FERTILIZER_NAME}`,
            availableFertilizer <= 0 ? '化肥已用完' : `剩余${availableFertilizer}个`
        ].join('\n'))
    }
} 